<template>
  <div v-if="!loading" class="all-box">

    <div class="all-box-left">

      <el-card :class="{'left-box':true, 'left-box-normal': !scrolled, 'left-box-scrolled': scrolled}" style="width: 250px">

        <div v-for="item in postForm.data.groupList" v-if="item.quList.length > 0" :key="item.id" class="group-card">
          <div>
            <div style="line-height: 40px">
              <el-button style="font-size: 14px; font-weight: 700" type="text" @click="goAnchor(item.id)">{{ item.title }}</el-button>
              <el-divider />
            </div>
            <div class="group-card-body">
              <div>
                共 <i class="num">{{ item.quCount }}</i> 题，共 <i class="num">{{ item.totalScore }}</i> 分
              </div>
            </div>

            <div class="card-box">
              <div v-for="card in item.quList" :key="card.id" class="item" @click="goAnchor(card.id)">
                <div :class="{num:true, right: card.isRight, error: !card.isRight}">{{ card.sort }}</div>
              </div>
            </div>

          </div>

        </div>

      </el-card>

    </div>

    <div class="all-box-center">

      <div style="padding-bottom: 20px">
        <el-alert v-if="postForm.settled" title="温馨提示：本试卷已完成出分结算流程，现已进入锁定状态，无法继续进行审阅和给分操作。" type="error"/>
        <el-alert v-else title="温馨提示：仅需修正确有不当之处的阅卷给分，并说明具体理由；若评分合理，则无需作任何更改。" type="info"/>
      </div>

      <template v-for="item in postForm.data.groupList" v-if="item.quList.length> 0">

        <el-card v-if="true" :id="item.id" :key="item.id" class="content-card">

          <template v-for="(qu,index) in item.quList">
            <div v-if="true" :id="qu.id" :key="qu.id" class="list-box">
              <div class="list-qu">
                <qu-item-show
                  :value="qu" :index="index"
                  :state="postForm.data.state"
                  :show-give="true"/>

                <div v-if="qu.quType === 'mix'">

                  <!-- 子题目的判卷 -->
                  <div v-for="(sub,jj) in qu.subList" :key="sub.id" class="list-sub-box">
                    <div class="list-sub-qu">
                      <qu-item-show
                        :value="sub" :index="jj"
                        :state="postForm.data.state"
                        :show-type="true"
                        :sub="true"
                        :show-give="true"/>
                    </div>

                    <div v-if="sub.manual" class="list-sub-opt">
                      <div class="check-box">
                        <div class="item">题目总分：{{ sub.score }}</div>
                        <div class="item">阅卷分数：{{ sub.giveScore || '未批阅' }}</div>
                        <div v-if="requireAudit">
                          <div class="item">审阅分数：</div>
                          <div class="item"><el-input-number :min="0" :disabled="postForm.settled" v-model="sub.fixScore" :precision="1" :max="sub.score" size="mini" style="width:100%" /></div>
                          <div class="item">审阅理由：</div>
                          <div class="item"><el-input v-model="sub.fixReason" :disabled="postForm.settled" type="textarea" size="mini" style="width:100%" /></div>
                        </div>
                      </div>

                    </div>

                  </div>

                </div>
              </div>

              <!-- 组合题不需要大题判卷 -->
              <div v-if="qu.quType!=='mix' && qu.manual" class="list-opt">

                <div class="check-box">
                  <div class="item">题目总分：{{ qu.score }}</div>
                  <div class="item">阅卷分数：{{ qu.giveScore || '未批阅' }}</div>
                  <div v-if="requireAudit">
                    <div class="item">审阅分数：</div>
                    <div class="item"><el-input-number :disabled="postForm.settled" :min="0" v-model="qu.fixScore" :precision="1" :max="qu.score" size="mini" style="width:100%" /></div>
                    <div class="item">审阅理由：</div>
                    <div class="item"><el-input v-model="qu.fixReason" :disabled="postForm.settled" type="textarea" size="mini" style="width:100%" /></div>
                  </div>

                </div>
              </div>
            </div>
          </template>

        </el-card>

      </template>

    </div>

    <div class="all-box-right">

      <el-card v-if="!loading" :class="{'left-box':true, 'left-box-normal': !scrolled, 'left-box-scrolled': scrolled}">

        <div class="tt">考试名称</div>
        <div>{{ postForm.data.title }}</div>

        <div v-if="postForm.data.userId">
          <div class="tt">考生姓名</div>
          <div class="tc">{{ postForm.data.userId_dictText }}</div>
        </div>

        <div class="tt">试卷编号</div>
        <div class="tc">{{ postForm.data.id }}</div>

        <div class="tt">考试时间</div>
        <div class="tc">{{ postForm.data.createTime }}</div>

        <div class="tt">交卷时间</div>
        <div class="tc">{{ postForm.data.handTime }}</div>

        <el-divider />


        <div class="tt">显示客观题</div>
        <div>
          <el-switch
            v-model="withObject"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </div>
        <el-divider />


        <div v-if="requireAudit && !!!postForm.settled">
          <div v-permission="['exam:review:paper:audit']" >
            <el-checkbox v-model="passAudit">自动通过审阅</el-checkbox>
          </div>
          <div>
            <el-checkbox v-model="autoNext">自动跳到下个</el-checkbox>
          </div>
          <el-button v-permission="['exam:review:paper:audit']" type="primary" style="margin-top: 20px" @click="submitForm">保存审阅</el-button>
        </div>
      </el-card>
    </div>

  </div>

</template>

<script>

import { scrollTo } from '@/utils/scroll-to'
import { paperAuditDetail, nextAuditPaper } from '@/api/exam/review'
import QuItemShow from '@/views/admin/repo/qu/components/QuItemShow'
import { submitFix } from '@/api/exam/review/qu'
import permission from '@/directive/permission'
import { Loading } from 'element-ui'

export default {
  directives: { permission },
  components: { QuItemShow },
  data() {
    return {
      // 查询参数
      examId: '',
      paperId: '',
      autoNext: false,
      requireAudit: false,
      passAudit: false,
      withObject: '0',
      scrolled: false,
      postForm: {
        settled: false,
        data: {
          groupList: []
        },
        examId: '',
        paperId: ''
      },
      loading: false,
      loadingDialog: null,
      fixMap: new Map()
    }
  },

  watch: {

    // 手动显示加载框
    loading: {
      handler(val) {
        if (val) {
          this.loadingDialog = Loading.service({
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        } else {
          if (this.loadingDialog) {
            this.loadingDialog.close()
          }
        }
      }
    },

    // 阅卷变化加入Map中
    'postForm.data.groupList': {
      handler(val) {
        if (!val && this.loading) {
          return
        }
        for (let i = 0; i < val.length; i++) {
          const quList = val[i].quList
          for (let j = 0; j < quList.length; j++) {
            const qu = quList[j]
            // 变动加入判题列表，注意这个ID为试卷的el_paper_qu.id
            if (qu.manual) {
              if (qu.fixScore != null) {
                this.fixMap.set(qu.id, { id: qu.id, quId: qu.quId, fixScore: qu.fixScore, fixReason: qu.fixReason })
              } else {
                this.fixMap.delete(qu.id)
              }
            }


            // 组合题增加组合分数
            if (qu.quType === 'mix') {
              const subList = qu.subList
              for (let k = 0; k < subList.length; k++) {
                const sub = subList[k]
                // 加入列表
                if (sub.manual) {
                  if (sub.fixScore != null) {
                    this.fixMap.set(sub.id, { id: sub.id, quId: sub.quId, fixScore: sub.fixScore, fixReason: sub.fixReason })
                  } else {
                    this.fixMap.delete(sub.id)
                  }
                }
              }
            }
          }
        }
      },
      deep: true
    },

    withObject: {
      handler() {
        this.fetchData()
      }
    }

  },

  mounted() {
    // 监听滚动条
    window.addEventListener('scroll', () => {
      let scrollTop = 0
      if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop
      } else if (document.body) {
        scrollTop = document.body.scrollTop
      }

      if (scrollTop > 85) {
        this.scrolled = true
      } else {
        this.scrolled = false
      }
    })
  },
  created() {
    this.examId = this.$route.query.examId
    this.paperId = this.$route.query.paperId
    this.reviewBy = this.$route.query.reviewBy
    this.requireAudit = this.$route.query.requireAudit && this.$route.query.requireAudit === '1'
    this.fetchData()
  },

  methods: {

    // 到指定位置
    goAnchor(selector) {
      const anchor = document.getElementById(selector)
      const to = anchor.offsetTop + 80
      scrollTo(to, 600, function() {
        console.log('滑动到指定位置！')
      })
    },

    // 获取试卷内容
    fetchData() {
      const withObject = this.withObject ? 1 : 0
      const params = { examId: this.examId, paperId: this.paperId, withObject: withObject, reviewBy: this.reviewBy }
      this.loading = true
      paperAuditDetail(params).then(res => {
        if (!res.data) {
          this.$notify({
            title: '成功',
            message: '没有可批阅的试卷啦！',
            type: 'success',
            duration: 2000
          })
          this.backToList()
          return
        }
        // 试卷内容
        this.postForm = res.data
        setTimeout(() => { this.loading = false }, 500)
      }).catch(() => {
        this.loading = false
      })
    },

    submitForm() {
      console.log('+++++审阅数据：', this.fixMap)

      // 组合批阅记录
      const params = {
        examId: this.examId,
        paperId: this.paperId,
        passAudit: this.passAudit,
        reviewQuList: Array.from(this.fixMap.values())
      }
      this.loading = true

      submitFix(params).then(() => {
        if (this.autoNext) {
          this.handleNext()
          return
        }
        this.$notify({
          title: '成功',
          message: '审阅提交成功！',
          type: 'success',
          duration: 2000
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 回到列表
     */
    backToList() {
      this.loading = false
      setTimeout(() => {
        this.$router.push({ name: 'ReviewPaperList', query: { examId: this.examId }})
      }, 1500)
    },

    // 下一个试卷
    handleNext() {
      nextAuditPaper({ paperId: this.paperId, examId: this.examId }).then(res => {
        const data = res.data
        if (!data.id) {
          this.$message.info('所有试卷都审阅完啦！')
          setTimeout(this.backToList, 1500)
        } else {
          this.$message.info('审阅成功，2秒后跳转到下一个试卷！')
          setTimeout(() => {
            // 替换数据
            this.paperId = data.id
            this.fetchData()
          }, 1500)
        }
      })
    }
  }
}
</script>

<style scoped>

.all-box{
  display: flex;
  flex-direction: row
}

.all-box-left{
  width: 250px;
  flex: 0 0 250px
}

.all-box-center{
  flex-grow: 1;
  padding-left: 20px;
  padding-right: 20px;
  width: 50vw;
}

.all-box-right{

  width: 220px;
  flex: 0 0 220px;
  text-align: left;
  line-height: 36px;
  font-size: 14px;
  font-weight: 700;
}

.all-box-right .el-card{
  width: 220px;
}

.all-box-right .el-card .tt{
  color: #1890FF;
  font-weight: 700;
}

.all-box-right .el-card .tc{
  color: #666;
  line-height: 22px;
  font-size: 14px;
}


.group-card{
  margin-bottom: 15px;
  line-height: 28px;
  width: 100%;
}

.group-card-body {
  line-height: 22px;
  font-size: 14px;
}

.group-card .num{
  color: #1890FF;
}

.left-box{
  height: calc(100vh - 120px);
  position: fixed;
  overflow: auto;
  clear: both;
}

.left-box-normal{
  top: 103px;
}

.left-box-scrolled{
  top: 20px;
  height: calc(100vh - 40px);
}

.content-card{
  margin-bottom: 20px;
  line-height: 28px;
}

.check-box{
  background: #f5f5f5;
  padding: 20px;
  line-height: 40px;
  width: 200px;
  font-size: 14px;
  font-weight: 700;
}

.check-box .item{
  display: flex;
  flex-direction: row;
  align-items: center;
}

.check-icon{
  font-size: 28px;
  color:#ddd;
  cursor: pointer;
  margin-right: 10px;
}

.check-icon-right{
  color: #03DD6D;
}

.check-icon-error{
  color: #FF4B50;
}

::v-deep .el-divider--horizontal{
  margin: 5px 0;
}

.link-item{
  background: #f5f5f5; margin-bottom: 10px; padding: 10px; border-radius: 10px
}

</style>
